import os
import json
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow

# YouTube Data API v3 设置
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'
CLIENT_SECRETS_FILE = 'client_secret.json'  # 你的API凭证文件
SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']

def get_authenticated_service():
    """获取认证的YouTube API服务"""
    flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
    credentials = flow.run_local_server(port=0)
    return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)

def get_video_comments(youtube, video_id, max_results=100):
    """获取视频评论"""
    comments = []
    results = youtube.commentThreads().list(
        part="snippet",
        videoId=video_id,
        maxResults=max_results,
        textFormat="plainText"
    ).execute()
    
    while results:
        for item in results['items']:
            comment = item['snippet']['topLevelComment']['snippet']
            comments.append({
                'author': comment['authorDisplayName'],
                'text': comment['textDisplay'],
                'published_at': comment['publishedAt'],
                'like_count': comment['likeCount']
            })
        
        # 检查是否有更多评论
        if 'nextPageToken' in results:
            next_page_token = results['nextPageToken']
            results = youtube.commentThreads().list(
                part="snippet",
                videoId=video_id,
                maxResults=max_results,
                pageToken=next_page_token,
                textFormat="plainText"
            ).execute()
        else:
            break
    
    return comments

def save_comments_to_file(comments, filename='comments.json'):
    """保存评论到JSON文件"""
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(comments, f, ensure_ascii=False, indent=2)

def main():
    # 设置视频ID和要获取的评论数量
    video_id = 'l7S3fTAZUgk'  # 替换为你要爬取的视频ID
    max_comments = 500  # 想要获取的评论数量
    
    try:
        # 获取认证服务
        youtube = get_authenticated_service()
        
        # 获取评论
        print(f"正在获取视频 {video_id} 的评论...")
        comments = get_video_comments(youtube, video_id, max_comments)
        
        # 保存评论
        output_file = f'comments_{video_id}.json'
        save_comments_to_file(comments, output_file)
        print(f"成功获取 {len(comments)} 条评论，已保存到 {output_file}")
        
    except Exception as e:
        print(f"发生错误: {str(e)}")

if __name__ == '__main__':
    main()